import re
from rest_framework import serializers
from user.models import User, ThreeLogin, UserVerify, UserProfile


class UserProfileSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""
    
    # 用户基本信息
    user_id = serializers.ReadOnlyField(source='user.id')
    username = serializers.ReadOnlyField(source='user.username')
    phone = serializers.ReadOnlyField(source='user.phone')
    email = serializers.ReadOnlyField(source='user.email')
    
    # Choice字段的显示值
    get_gender_display = serializers.ReadOnlyField()
    get_fitness_goal_display = serializers.ReadOnlyField()
    get_fitness_level_display = serializers.ReadOnlyField()
    get_dietary_preference_display = serializers.ReadOnlyField()
    get_activity_level_display = serializers.ReadOnlyField()
    
    # 计算属性
    age = serializers.ReadOnlyField()
    bmi = serializers.ReadOnlyField()
    bmi_category = serializers.ReadOnlyField()
    
    class Meta:
        model = UserProfile
        fields = [
            'id',
            'user_id',
            'username',
            'phone',
            'email',
            'nickname',
            'avatar',
            'logo_url',
            'gender',
            'get_gender_display',
            'birth_date',
            'height',
            'weight',
            'fitness_goal',
            'get_fitness_goal_display',
            'fitness_level',
            'get_fitness_level_display',
            'dietary_preference',
            'get_dietary_preference_display',
            'activity_level',
            'get_activity_level_display',
            'has_diabetes',
            'has_hypertension',
            'has_heart_disease',
            'food_allergies',
            'dietary_restrictions',
            'preferred_workout_duration',
            'preferred_workout_times',
            'created_at',
            'updated_at',
            'age',
            'bmi',
            'bmi_category'
        ]
        read_only_fields = ['id', 'user_id', 'username', 'phone', 'email', 'created_at', 'updated_at', 'age', 'bmi', 'bmi_category']

class UserSerializer(serializers.ModelSerializer):
    """用户基本信息序列化器"""
    
    class Meta:
        model = User
        fields = ['id', 'username', 'phone', 'email', 'date_joined']
        read_only_fields = ['id', 'date_joined']


class ThreeLoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = ThreeLogin
        fields = '__all__'


class SendSMSSerializer(serializers.Serializer):
    phone = serializers.CharField(
        max_length=11,
        min_length=11,
        required=True,
        error_messages={
            'required': '手机号不能为空',
            'min_length': '手机号长度必须为11位',
            'max_length': '手机号长度必须为11位'
        }
    )
    code = serializers.CharField(
        max_length=4,
        min_length=4,
        required=True,
        error_messages={
            'required': '图片验证码不能为空',
            'min_length': '图片验证码长度必须为4位',
            'max_length': '图片验证码长度必须为4位'
        }
    )

    def validate_phone(self, value):
        """验证手机号格式"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_code(self, value):
        """验证图片验证码格式"""
        # 允许字母和数字的组合，长度为4位
        if not re.match(r'^[A-Z0-9]{4}$', value.upper()):
            raise serializers.ValidationError('图片验证码格式不正确，应为4位字母或数字')
        return value.upper()  # 统一转为大写


class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField(
        max_length=11,
        min_length=11,
        required=True,
        error_messages={
            'required': '手机号不能为空',
            'min_length': '手机号长度必须为11位',
            'max_length': '手机号长度必须为11位'
        }
    )
    sms_code = serializers.CharField(
        max_length=4,
        min_length=4,
        required=True,
        error_messages={
            'required': '短信验证码不能为空',
            'min_length': '验证码长度必须为4位',
            'max_length': '验证码长度必须为4位'
        }
    )

    def validate_phone(self, value):
        """验证手机号格式"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_sms_code(self, value):
        """验证验证码格式"""
        if not value.isdigit():
            raise serializers.ValidationError('验证码必须为数字')
        return value



class UserVerifySerializer(serializers.ModelSerializer):

    class Meta:
        model = UserVerify
        fields = '__all__'